$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_fblx_m")
    const dgrid1 = $NG.getCmpApi("p_form_fblx_d2")
    const dgrid2 = $NG.getCmpApi("p_form_fblx_d1")
    const dgrid3 = $NG.getCmpApi("p_form_fblx_d3")
    const getHeadValue = (str) => mstform.getItem(str).getValue()
    const config = {
        list_data_bak: []

    }
    setTimeout(()=>{
        getFbchFilter()
    },200)
    GctsFilter()
    if (page.isList) {
        setInterval(() => {
            let bigBox = $NG.getCmpApi("grid")?.getRef()?.bodyRef.current
            const start = new Date().getTime()
            let dom = bigBox.childNodes[0].childNodes[0]
            // while(new Date().getTime() - start < 10 * 1000 && !dom){
            //     dom = document.childNodes[0].childNodes[0]
            // }
            // if(!dom){
            //     $NG.alert("发生异常！")
            // }
            if (!dom) {
                return
            }
            dom.childNodes.forEach(el => {
                let colorLock = false
                // console.log(`el`,el);
                el.childNodes.forEach(it => {
                    if (it.getAttribute("data-key") == 'u_ykqk') {
                        const minDom = it.childNodes[0]?.textContent
                        if ((Number(minDom) || 0) < 0) {
                            colorLock = true
                        }
                    }
                })
                if (colorLock) {
                    el.childNodes.forEach(item => {
                        item.style.background = '#ff000038'
                    })
                }
            })
        }, 1000)
    }

    useValuesChange(() => {
        getProjectInfoByPhid()
        FblxName()
    }, "p_form_fblx_m.phid_pc")

    function getProjectInfoByPhid() {
        const phid = mstform.getItem("phid_pc").getValue()
        if (!phid) return
        $NG.execServer("getProjectInfoByPhid", { phid }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            if (datas.phid_org == 1) {
                mstform.getItem("u_xnblb").setValue('01')
            } else {
                mstform.getItem("u_xnblb").setValue("02")
            }
        })
    }

    useUpdateRows(() => {
        sumAmt()
        console.log(`测试`,);
    }, "p_form_fblx_d2")
    useUpdateRows(()=>{
        sumAmt()
        console.log(`测试3`,);
    },"p_form_fblx_d3")

    useValuesChange(async () => {
        GctsFilter()
        getFbchDetail2()
        getFbchDetail1()
        mstform.getItem("u_gctssxbh").setValue({ label: null, value: null })
        const phid = getHeadValue("u_fbxmchsbh")
        if (!phid) return
        const res = await $NG.execServer("SELECT", { sql: `select m.phid_pc, project.bill_name from p_form_fbch_m m left join project_table project on project.phid = m.phid_pc where m.phid = '${phid}'` })
        if (res.count == 0) return
        const datas = JSON.parse(res.data)[0].extendObjects
        mstform.getItem("phid_pc").setValue({
            label: datas.bill_name,
            value: datas.phid_pc
        })
    }, "u_fbxmchsbh")


    function sumAmt(rowsd) {
        let rows = []
        if (!rowsd) {
            rows = dgrid3.getRows()
        } else {
            rows = rowsd
        }
        let total_amt = 0
        let total_amt_cb = 0
        rows.forEach(el => {
            el.u_fyxj = (Number(el.u_cl) || 0) + (Number(el.u_jx) || 0) + (Number(el.u_qtfy) || 0) + (Number(el.u_sj) || 0)
            el.u_dydcbhtje = (Number(el.u_gcl) || 0) * (Number(el.u_dj) || 0)
            el.u_yfb1 = (Number(el.u_nfb) || 0) * (Number(el.u_gcl) || 0)
            el.u_lr1 = (Number(el.u_dydcbhtje) || 0) - (Number(el.u_yfb1) || 0) - (Number(el.u_fyxj) || 0)
            el.u_lr = (Number(el.u_lr1) || 0) / (Number(el.u_gcl) || 0)
            el.u_cl1 = (Number(el.u_cl) || 0) * (Number(el.u_gcl) || 0)
            el.u_jx1 = (Number(el.u_jx) || 0) * (Number(el.u_gcl) || 0)
            el.u_qtfy1 = (Number(el.u_qtfy) || 0) * (Number(el.u_gcl) || 0)
            el.u_sj1 = (Number(el.u_sj) || 0) * (Number(el.u_gcl) || 0)
            el.u_fyxj1 = (Number(el.u_cl1) || 0) + (Number(el.u_jx1) || 0) + (Number(el.u_qtfy1) || 0) + (Number(el.u_sj1) || 0)
            el.u_hj = (Number(el.u_gcl) || 0) * (Number(el.u_dj) || 0)
        })
        // 拆解
        const items = flattenAndDeduplicate(rows)
        items.forEach(el => {
            total_amt += (Number(el.u_yfb1) || 0)
            total_amt_cb += (Number(el.u_dydcbhtje) || 0)
        })
        mstform.getItem("u_yjfbzje").setValue((Number((total_amt).toFixed(4)) || 0))
        mstform.getItem("u_dycbhtje").setValue((Number((total_amt_cb).toFixed(4)) || 0))
        mstform.getItem("u_ykqk").setValue(total_amt_cb - total_amt)
        if (total_amt < 10000 * 1000) {
            mstform.getItem("u_gjfbgcjk").setValue("不超过1000万元")
        } else {
            mstform.getItem("u_gjfbgcjk").setValue("1000万元以上")
        }
        dgrid2.refreshView()
    }

    function getFbchDetail1() {
        const phid = mstform.getItem("u_fbxmchsbh").getValue()
        if (!phid) return
        $NG.execServer("SELECT", { sql: `select d.rel_key1,d.u_fbxmmc from p_form_fbch_d2 d left join p_form_fbch_m m on m.phid=d.pphid where m.phid = '${phid}'` }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data).reduce((value, item) => {
                const it = item.extendObjects
                value.push({
                    ...it,
                    u_fblxmc: it.u_fbxmmc
                })
                return value
            }, [])
            dgrid2.clearRows().then(() => {
                dgrid2.addRows(datas)
            })
        })
    }

    function getFbchDetail2() {
        const phid = mstform.getItem("u_fbxmchsbh").getValue()
        if (!phid) return
        $NG.execServer("getFbchDetail2", { phid }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data).reduce((value, item) => {
                const it = item.extendObjects
                value.push({
                    ...it,
                    u_wbs: it.u_wbs,
                    u_wbs_EXName: it.u_wbs_exname,
                    u_dw: it.u_dw,
                    u_dw_EXName: it.msname,
                    u_cl1: it.u_clje,
                    u_lr1: it.u_lrje,
                    u_yfb1: it.u_nfb,
                    u_dydcbhtje: it.u_dydcbhtje,
                    u_jx1: it.jxje,
                    u_qtfy1: it.u_qtfyje,
                    u_sj1: it.u_sjje,
                    u_fyxj1: it.u_fyxjje,
                    u_bz: it.u_bz
                })
                return value
            }, [])
            sumAmt(datas)
            let arr = arrayToTree(datas, "s_tree_id", "s_tree_pid")
            dgrid1.clearRows().then(() => {
                dgrid1.addRows(arr)
            })
        })
    }
    // 转属性结构
    function arrayToTree(items, idField = "id", parentField = "parentId", childrenField = "children") {
        const map = {};
        const roots = [];

        // 先建立 id → item 的映射
        items.forEach(item => {
            map[item[idField]] = { ...item, [childrenField]: [] };
        });

        // 组装树
        items.forEach(item => {
            const parentId = item[parentField];
            if (parentId == null || parentId.length < 2 || parentField == '0') {
                // 根节点
                roots.push(map[item[idField]]);
            } else if (map[parentId]) {
                // 挂到父节点的 children 上
                map[parentId][childrenField].push(map[item[idField]]);
            }
        });

        return roots;
    }

    // 过滤分包项目名称
    FblxName()
    function FblxName(){
        const phid = mstform.getItem("phid_pc").getValue()
        mstform.getItem("u_fbxmmc").setProps({
                onBeforeOpen: async () => {
                    if (!phid) {
                        $NG.alert("请选择工程项目名称！");
                        return false;
                    }
                },
                clientSqlFilter: {
                    'p_form_fbch_m.phid_pc': phid,
                }
            });
    }
    function GctsFilter() {
        try {
            mstform.getItem("u_gctssxbh").setProps({
                onBeforeOpen: async () => {
                    var u_fbxmchsbh = getHeadValue("u_fbxmchsbh")
                    if (!u_fbxmchsbh) {
                        $NG.alert("请选择分包项目策划书编号！");
                        return false;
                    } else {
                        return true;
                    }
                },
                clientSqlFilter: {
                    u_fbxmchsbh: getHeadValue("u_fbxmchsbh"),
                }
            });
        } catch (err) {
            console.log(`错误`, err);
        }
    }

    async function getFbchFilter(){
        if(page.oType == 'view') return 
        const currentPhid = mstform.getValues().u_chmc
        const res = await $NG.execServer("SELECT",{sql:`select u_chmc from p_form_fblx_m where ${currentPhid?"u_chmc='"+currentPhid+"'":'1=1'}`})
        const phids = JSON.parse(res.data).reduce((value,item)=>{
            value.push(item.extendObjects)
            return value
        },[])
        console.log(`phids`,phid);
        mstform.getItem("u_chmc").setProps({
            clientSqlFilter:`phid in (${phids.join(",")})`
        })
    }

    function flattenAndDeduplicate(arr) {
        const result = [];
        const seenTreeIds = new Set(); // 用于记录已出现的s_tree_id

        // 深拷贝函数：确保对象地址改变
        function deepCopy(obj) {
            if (typeof obj !== 'object' || obj === null) {
                return obj;
            }
            if (Array.isArray(obj)) {
                return obj.map(item => deepCopy(item));
            }
            const copy = {};
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    copy[key] = deepCopy(obj[key]);
                }
            }
            return copy;
        }

        // 递归提取并去重
        function traverse(elements) {
            elements.forEach(element => {
                // 深拷贝当前对象（地址改变）
                const copied = deepCopy(element);

                // 检查s_tree_id是否已存在，不存在则保留
                if (!seenTreeIds.has(copied.s_tree_id)) {
                    seenTreeIds.add(copied.s_tree_id);
                    result.push(copied);
                }

                // 无论当前对象是否被保留，都要递归处理children（避免遗漏子层级）
                if (element.children && Array.isArray(element.children)) {
                    traverse(element.children);
                }
            });
        }

        traverse(arr);
        return result;
    }
})